const Router = require('koa-router');
const router = new Router();

router.get('/', async ctx => {
    const { getUser } = require('../models/user');
    const user_res = await getUser(ctx.access_token)
    ctx.errcode(user_res.data.errcode, user_res.data.errmsg)
    
    ctx.body = {
        code: 200,
        data: user_res.data.data.map(item => JSON.parse(item)),
        msg: 'ok'
    };
})
router.get('/:id', async ctx => {
    const { getInfo } = require('../models/user');
    const user_res = await getInfo(ctx.access_token, ctx.params.id)
    console.log(user_res.data)
    ctx.errcode(user_res.data.errcode, user_res.data.errmsg)
    console.log()
    ctx.body = {
        code: 200,
        data: (user_res.data.data.map(item => JSON.parse(item)))[0],
        msg: 'ok'
    };
})
router.post('/', async ctx => {
    const { addUser } = require('../models/user');
    const user_res = await addUser(ctx.access_token, ctx.request.body)
    ctx.errcode(user_res.data.errcode, user_res.data.errmsg)
    ctx.body = {
        code: 200,
        data: user_res.data,
        msg: 'ok'
    };
})
router.delete('/', async ctx => {
    const { delUser } = require('../models/user');
    const user_res = await delUser(ctx.access_token, ctx.query.id)
    ctx.errcode(user_res.data.errcode, user_res.data.errmsg)
    ctx.body = {
        code: 200,
        data: user_res.data,
        msg: 'ok'
    };
})
router.put('/', async ctx => {
    const { updateUser } = require('../models/user');
    const user_res = await updateUser(ctx.access_token, ctx.request.body)
    console.log(user_res.data)
    ctx.errcode(user_res.data.errcode, user_res.data.errmsg)
    ctx.body = {
        code: 200,
        data: user_res.data,
        msg: 'ok'
    };
})

module.exports = router.routes();